import Meta from "../../components/Meta";
import Header from "../../components/Header/Header";
import Nav from "../../components/Nav/Nav";
import Footer from "../../components/Footer/Footer";
import { transData } from "../../utils/tool";
import { request } from "../../utils/request";
import { Form, Input, Row, Col, Button, Alert } from "antd";
import styles from "./register.module.scss";
import { EyeInvisibleOutlined, EyeTwoTone } from "@ant-design/icons";
import { useState } from "react";
import CryptoJs from 'crypto-js';
import { useRouter } from 'next/router';

export default function Account(props) {
  const router = useRouter();
  console.log('router',router)
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)
  const [errMsg, setMsg] = useState()
  const [isLogin, setLogin] = useState(true)

  const onFinish = async (value) => {
    value.password = CryptoJs.MD5(value.password).toString();

    setLoading(true)
    const ret = isLogin ?
      await request(`${props.apiUrl}/api/auth/userLogin`, value)
      : await request(`${props.apiUrl}/api/user/register`, value);

    console.log('ret,ret', ret)
    setLoading(false)
    if (ret.success) {
      setMsg('')
      //如果登录表单
      if (isLogin) {
        localStorage.setItem('token', ret.data.token)
        const res = await request(`${props.apiUrl}/api/user/currentUser`, {})
        if (res.code === 100000) {
          localStorage.setItem('user', JSON.stringify(res.data))

        }
        if(router?.query?.back){
          router.replace(router.query.back)
        } else {
          router.replace('/account')
        }
        

      } else {
        setLogin(true)
      }
    } else {
      setMsg(ret.data.message)
    }
  };
  const onFinishFailed = () => { };
  const validatePassword = (rule, value, callback) => {
    console.log('value', value)
    // 校验密码强度
    // 1. 必须同时包含大写字母、小写字母和数字，三种组合
    // 2. 长度在8-30之间
    const passwordReg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/;
    if (value) {
      if (!passwordReg.test(value)) {
        callback('please enter corret pasword');
      }
      if (value.length < 8 || value.length > 16) {
        callback('please enter corret pasword')
      }
    }
    callback();
  };
  return (
    <>
      <Meta>
        <title>NINAMOKA-SignIn</title>
      </Meta>
      <Header />
      <Nav navData={props.navData} />
      <div className="container">

        <p className={styles["r-title"]}>
          {isLogin ? 'Sign in to your account' : 'Create a NinaMoka account'}
        </p>

        <Row>
          <Col xs={24} md={8}></Col>
          <Col xs={24} md={8}>
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item>
                {errMsg && <Alert
                  message="Error"
                  description={errMsg}
                  type="error"
                  showIcon
                />
                }
              </Form.Item>
              <Form.Item
                label="E-MAIL"
                name="username"
                rules={[
                  {
                    required: true,
                    message: "Email address is not in the correct format (xxx@yyy.zzz). Please correct the email address",
                    type: 'email'
                  },
                ]}
              >
                <Input size="large" />
              </Form.Item>
              <Form.Item
                label="PASSWORD"
                name="password"
                rules={[
                  {
                    required: true,
                    message: "Password is not in the correct format",
                    validator: (rule, value, callback) => { validatePassword(rule, value, callback) }
                  },
                ]}
              >
                <Input.Password
                  size="large"
                  placeholder="Please enter your password"
                  iconRender={(visible) =>
                    visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
                  }
                />
              </Form.Item>
              {!isLogin ? <Form.Item>
                <div className={styles.password}>
                  <span>8-16 characters</span>
                  <span>At least 1 uppercase</span>
                </div>
                <div className={styles.password}>
                  <span>At least 1 lowercase</span>
                  <span>At least 1 digit</span>
                </div>
              </Form.Item> : ''}
              <Form.Item>
                <Button type="primary" size="large" htmlType="submit" block loading={loading}>{isLogin ? 'Sign In' : 'Create account'}</Button>
              </Form.Item>
              {isLogin ? <Form.Item>
                <span className={styles['text-reg']} onClick={() => setLogin(false)}>Create a Ninamoka account</span>
              </Form.Item> :
                <Form.Item><span className={styles['text-reg']} onClick={() => setLogin(true)}>Sign in to your account</span></Form.Item>}
            </Form>

          </Col>
          <Col xs={24} md={8}></Col>
        </Row>
      </div>
      <Footer navData={props.navData} siteData={props.siteInfo}/>
    </>
  );
}
export async function getServerSideProps(params) {
  const apiUrl = process.env.APIURL;
  console.log('apiurl', apiUrl)

  const navData = await request(`${apiUrl}/api/client/nav`);
  const newNavData = transData(navData.data, "id", "pid");
  const siteInfo = await request(`${apiUrl}/api/client/querySiteInfo`);
  return {
    props: {
      navData: newNavData,
      apiUrl,
      siteInfo:siteInfo.data
    },
    // Re-generate the post at most once per second
    // if a request comes in

  };
}
